/**
 * Created by tdzl2003 on 6/19/16.
 */
import React, { PropTypes } from 'react';
import {
  TextInput,
} from 'react-native';
import FormContext from './FormContext';

export default class FormInput extends React.Component {
  static propTypes = {
    ...TextInput.propTypes,
    name: PropTypes.string.isRequired,
  }
  static contextTypes = {
    form: PropTypes.instanceOf(FormContext),
  };

  componentWillMount() {
    this.context.form.addField(this.props.name, this);
  }

  componentWillReceiveProps(newProps) {
    if (newProps.name !== this.props.name) {
      this.context.form.removeField(this.props.name);
      this.context.form.addField(newProps.name, this);
    }
  }

  componentWillUnmount() {
    this.context.form.removeField(this.props.name);
  }

  onChangeText = value => {
    const { name, onChangeText } = this.props;
    const { form } = this.context;
    if (form.getValue(name) !== value) {
      form.setValue(name, value);
      if (onChangeText) {
        onChangeText(value);
      }
      this.forceUpdate();
    }
  };

  get defaultValue() {
    return this.props.defaultValue;
  }

  validate(value) {
    const { validate, validateMessage } = this.props;
    if (!validate) {
      return;
    }
    if (typeof(validate) === 'function') {
      validate(value);
    } else if (typeof(validate.test) === 'function') {
      if (!validate.test(value || '')) {
        throw new Error(validateMessage || 'Form validation error.');
      }
    }
  }

  render() {
    return (
      <TextInput
        {...this.props}
        value={this.context.form.getValue(this.props.name)}
        onChangeText={this.onChangeText}
      />
    );
  }
}
